package db

import (
	"Nacos_GateWay/config"
	"Nacos_GateWay/utils"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"io/ioutil"
	"log"
	"strings"
)

var db *gorm.DB
var err error

/**
 *   gorm v2 版本初始化数据库
 */
func InitDB(dbConfig *config.Config) {
	log.Println("数据库初始化")
	dsn := dbConfig.GetString("gorm.username") + ":" + dbConfig.GetString("gorm.password") + "@tcp(" + dbConfig.GetString("gorm.address") + ")/" + dbConfig.GetString("gorm.dbname") + "?charset=utf8&parseTime=True&loc=Local"
	log.Println(dsn)
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{SingularTable: true}, //是否采用负数表名
		Logger:         logger.Default.LogMode(logger.Info),        //打印日志级别
	})
	if err != nil {
		log.Println(err)
		panic(err)
	}
	if HasTable("file_info") {
		log.Println("执行增量脚本")
		//excuteSqlScript(dbConfig.Sqlincrementpath)
	} else {
		log.Println("执行全量脚本")
		//excuteSqlScript(dbConfig.Sqlinitpath)
	}
}

//判断数据表是否存在，存在就执行增量SQL不存在就执行全量
func HasTable(tablename string) bool {
	var result int //
	db.Raw("select COUNT(*) from information_schema.TABLES where TABLE_NAME  = ?", tablename).Scan(&result)
	log.Println("##result.count =", result)
	if result > 0 {
		return true
	}
	return false
}

//加载SQL脚本
func excuteSqlScript(sqlpath string) {
	files := utils.GetFiles(sqlpath)
	if len(files) == 0 {
		panic("error 缺少sql脚本")
	}
	for _, path := range files {
		file, err := ioutil.ReadFile(path)
		if err != nil {
			panic(err)
		}
		str := string(file)
		str = strings.TrimSpace(str) //去除首尾空格
		sqlstr := strings.Split(str, ";")
		for _, sql := range sqlstr {
			if !strings.EqualFold(sql, "") {
				//不为空
				db.Exec(sql)
			}
		}

	}
}

func GetService() *gorm.DB {
	return db
}
